<!--
  * 支付链接新增/编辑弹窗
  *
  * @Author:    1024创新实验室
  * @Date:      2025-01-18
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
    <a-modal :title="form.id ? '编辑链接' : '新增链接'" :open="visible" :width="600" @ok="onSubmit" @cancel="onClose"
        :confirmLoading="submitLoading" destroyOnClose>
        <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
            <a-form-item label="货币" name="currencyId">
                <a-select placeholder="请选择货币" :showSearch="true" :allowClear="true" v-model:value="form.currencyId">
                    <a-select-option v-for="item in currencyList" :key="item.id" :value="item.id">
                        {{ item.name }}
                    </a-select-option>
                </a-select>
            </a-form-item>

            <a-form-item label="过期时间" name="expireTime">
                <a-date-picker v-model:value="form.expireTime" show-time placeholder="请选择过期时间" style="width: 100%"
                    format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <!--       
      <a-form-item label="是否有效" name="isValid">
        <a-select v-model:value="form.isValid" placeholder="请选择是否有效">
          <a-select-option :value="1">有效</a-select-option>
          <a-select-option :value="0">无效</a-select-option>
        </a-select>
      </a-form-item> -->

            <a-form-item label="备注" name="remark">
                <a-textarea v-model:value="form.remark" placeholder="请输入备注" :maxlength="60" :rows="3" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { updateGenerateLinkRecord, addGenerateLinkRecord, getCurrencyListByEmployeeId } from '/@/api/pay/pay-api';
import { smartSentry } from '/@/lib/smart-sentry';
import CurrencySelect from '/@/components/system/currency-select/index.vue';
import dayjs from 'dayjs';
import { useUserStore } from '/@/store/modules/system/user';

// =========== 属性定义 =============
const emit = defineEmits(['reloadList']);

// =========== 表单数据 =============
const visible = ref(false);
const submitLoading = ref(false);
const formRef = ref();

const formState = {
    id: undefined,
    employeeId: undefined,
    generatedLink: undefined,
    currencyId: undefined,
    expireTime: undefined,
    isValid: 1,
    remark: undefined,
};

const form = reactive({ ...formState });

// =========== 表单验证规则 =============
const rules = {
    employeeId: [
        { required: true, message: '请输入员工ID', trigger: 'blur' },
        { type: 'number', min: 1, message: '员工ID必须大于0', trigger: 'blur' },
    ],
    generatedLink: [
        { required: true, message: '请输入生成链接', trigger: 'blur' },
        { type: 'url', message: '请输入有效的链接地址', trigger: 'blur' },
    ],
    currencyId: [
        { required: true, message: '请选择货币', trigger: 'change' },
    ],
    expireTime: [
        { required: true, message: '请选择过期时间', trigger: 'change' },
    ],
    isValid: [
        { required: true, message: '请选择是否有效', trigger: 'change' },
    ],
};

// =========== 显示弹窗 =============
function showModal(record) {
    visible.value = true;
    if (record) {
        // 编辑模式
        Object.assign(form, {
            ...record,
            expireTime: record.expireTime ? dayjs(record.expireTime) : undefined,
        });
    } else {
        // 新增模式
        resetForm();
    }
    queryCurrencyList()
}

// =========== 重置表单 =============
function resetForm() {
    Object.assign(form, formState);
    formRef.value?.resetFields();
}

// =========== 提交表单 =============
async function onSubmit() {
    try {
        await formRef.value.validate();
        submitLoading.value = true;
        const employeeId = useUserStore()?.employeeId;
        const submitData = {
            ...form,
            employeeId,
            expireTime: form.expireTime ? dayjs(form.expireTime).format('YYYY-MM-DD HH:mm:ss') : undefined,
        };

        if (form.id) {
            // 编辑 - 使用 updateGenerateLinkRecord
            await updateGenerateLinkRecord(submitData);
            message.success('编辑成功');
        } else {
            // 新增 - 使用 addGenerateLinkRecord
            await addGenerateLinkRecord(submitData);
            message.success('新增成功');
        }

        emit('reloadList');
        onClose();
    } catch (e) {
        if (e.errorFields) {
            // 表单验证失败
            return;
        }
        smartSentry.captureError(e);
    } finally {
        submitLoading.value = false;
    }
}

const currencyList = ref([]);
async function queryCurrencyList() {
    console.log('useUserStore().userInfo', useUserStore());
    const employeeId = useUserStore()?.employeeId;
    const params = {
        employeeId,
    };
    const res = await getCurrencyListByEmployeeId(params);
    console.log('getCurrencyListByEmployeeId', res);
    currencyList.value = res.data;
}
// =========== 关闭弹窗 =============
function onClose() {
    visible.value = false;
    resetForm();
}

// =========== 暴露方法 =============
defineExpose({
    showModal,
});
</script>

<style lang="less" scoped>
// 可以添加自定义样式</style>
